<template>
    <div class="login-container">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="80px" class="login-form">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login('loginForm')">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import router from '@/router';
import request from '@/utils/request'
export default {
    data() {
        return {
            loginForm: {
                username: '123456',
                password: '123456'
            },
            loginRules: {
                username: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在6到16之间', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            }
        };
    },
    mounted() {
        this.refresh()
    },
    methods: {
        login(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // 表单验证通过，可以提交登录逻辑，例如发送请求等
                    console.log('表单验证通过');
                    request.post("http://localhost:9090/account/login", {
                        username: this.loginForm.username,
                        password: this.loginForm.password
                    })
                        .then(res => {
                            if(res.code == 200){
                                alert("登入成功");
                            console.log(res.data.token);
                            router.push("/")
                            localStorage.setItem('token', res.data.token);
                            // localStorage.setItem('userId', res.userId);
                            localStorage.setItem('userInfo', res.data.userInfo);
                            }else{
                                alert("账号密码错误");
                            }
                        })
                        .catch(error => {
                            if (error.response && error.response.status === 401) {
                                alert("账号密码错误");
                            } else {
                                // 其他错误，输出到控制台
                                console.error(error);
                            }
                        });
                } else {
                    // 表单验证不通过，不执行提交操作
                    this.$message({
                        message: '账号密码填写不规范',
                        type: 'error'
                    });
                    return false;
                }
            });
        },
        refresh() {
            // 从本地存储中获取存储的信息
            const token = localStorage.getItem('token');
            if (token) {
                const headers = {
                    'Authorization': `Bearer ${token}`
                };
                request.post("http://localhost:9090/account/refresh", {
                }, {
                    headers: headers
                })
                    .then(res => {
                        alert("登入成功");
                        router.push("/")
                        // 清除本地存储中的 token
                        localStorage.removeItem('token');
                        localStorage.setItem('token', res.data.token);
                        // localStorage.setItem('userId', res.userId);
                        localStorage.setItem('userInfo', res.data.userInfo);
                    });
            }
        }

    }
};
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.login-form {
    width: 300px;
}
</style>